package com.dfbz.dao;

import com.dfbz.dao.base.BaseDao;
import com.dfbz.model.Dept;
import com.dfbz.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.BeanMapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DeptDao extends BaseDao<Dept> {
    public DeptDao(){
        super(Dept.class);
    }

    public List<Dept> findAll(){
        String sql = "select * from dept";
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<Dept> deptList = new ArrayList<>();
        try {
            deptList = qr.query(sql, new BeanListHandler<>(Dept.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return deptList;
    }

    public List<Map<String, Object>> findUserList() {
        String sql = "SELECT u.id as user_id,IFNULL(ui.real_name,'IT大牛')as real_name,\n" +
                "u.dept_id,d.name as dept_name\n" +
                "FROM user u,user_info ui,dept d\n" +
                "where u.dept_id is not null and ui.user_id = u.id and u.dept_id = d.id";
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            list = qr.query(sql, new MapListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
